﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using SHZY.BaseData.Entitys.Common.Dto.Factory;
using SHZY.BaseData.Entitys.Common.Dto.Station;
using SHZY.BaseData.Entitys.Common.Entity;
using SHZY.BaseData.Interfaces.Common;
using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Interfaces.System;
using SqlSugar;

namespace SHZY.BaseData.Common;

/// <summary>
/// 业务实现：工位信息.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "QmsBaseStation", Order = 200)]
[Route("api/Common/BaseData/[controller]")]
public class ComBaseStationService : IComBaseStationService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<ComBaseStationEntity> _repository;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="ComBaseStationService"/>类型的新实例.
    /// </summary>
    public ComBaseStationService(
        ISqlSugarRepository<ComBaseStationEntity> qmsBaseStationRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = qmsBaseStationRepository;
        _dataInterfaceService = dataInterfaceService;
        _userManager = userManager;
    }

    /// <summary>
    /// 获取工位信息.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<ComBaseStationInfoOutput>();
    }

    /// <summary>
    /// 获取工位信息列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] ComBaseStationListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<ComBaseStationEntity, ComBaseFactorystructureEntity>((it, b) => new JoinQueryInfos(JoinType.Left, it.ParentId == b.Id))
            .WhereIF(!string.IsNullOrEmpty(input.parentId), (it, b) => b.Id.Equals(input.parentId))
            .WhereIF(!string.IsNullOrEmpty(input.enCode), (it, b) => it.EnCode.Contains(input.enCode))
            .WhereIF(!string.IsNullOrEmpty(input.fullName), (it, b) => it.FullName.Contains(input.fullName))
            .Where((it, b) => it.DeleteMark == null || it.DeleteMark == 0)
            .WhereIF(!string.IsNullOrEmpty(input.keyword), (it, b) => it.ParentId.Contains(input.keyword) || it.EnCode.Contains(input.keyword) || it.FullName.Contains(input.keyword))
             .Select((it, b) => new ComBaseStationListOutput
             {
                 id = it.Id,
                 enCode = it.EnCode,
                 fullName = it.FullName,
                 sortCode = it.SortCode,
                 description = it.Description,
                 enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "停用", "正常"),
                 parentId = b.FullName
             }).MergeTable();

        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        else
        {
            queryable.OrderBy(it=>it.id);
        }
        var data = await queryable.ToPagedListAsync(input.currentPage, input.pageSize);

        //await _repository.Context.ThenMapperAsync(data.list, async item =>
        //{
        //    // 工厂GUID
        //    var parentIdData = await _dataInterfaceService.GetDynamicList("", "id", "fullName", "children");
        //    if (parentIdData.Count > 0)
        //    {
        //        item.parentId = parentIdData.Find(it => it.id.Equals(item.parentId)).fullName;
        //    }

        //});

        return PageResult<ComBaseStationListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 获取工厂建模列表.
    /// </summary>
    /// <returns></returns>
    [HttpGet("GetListOption")]
    public async Task<dynamic> GetListOption()
    {
        var data = new List<QmsBaseFactorystructureListOptionOutput>();
        data = await _repository.Context.Queryable<ComBaseFactorystructureEntity>()
         .Where(it => it.Type.Equals("Workshop") && (it.DeleteMark == null || it.DeleteMark == 0))
           .OrderBy(it => it.Id)
           .Select(it => new QmsBaseFactorystructureListOptionOutput
           {
               id = it.Id,
               enCode = it.EnCode,
               fullName = it.FullName,
               parentId = it.ParentId,
               hasChildren = true,
               TreeNode = "1"
           }).ToListAsync();

        foreach (var item in data)
        {
            var enCode = item.id;
            item.children = await _repository.Context.Queryable<ComBaseFactorystructureEntity>().Where(w => w.ParentId == enCode)
               .Select(it => new QmsBaseFactorystructureListOptionOutput
               {
                   id = it.Id,
                   enCode = it.EnCode,
                   fullName = it.FullName,
                   parentId = it.ParentId,
                   hasChildren = true,
                   TreeNode = "2"
               }).ToListAsync();

            foreach (var item2 in item.children)
            {
                var enCode2 = item2.id;
                item2.children = await _repository.Context.Queryable<ComBaseFactorystructureEntity>().Where(w => w.ParentId == enCode2)
                   .Select(it => new QmsBaseFactorystructureListOptionOutput
                   {
                       id = it.Id,
                       enCode = it.EnCode,
                       fullName = it.FullName,
                       parentId = it.ParentId,
                       hasChildren = true,
                       TreeNode = "3"
                   }).ToListAsync();
            }
        }
        return data;
    }

    /// <summary>
    /// 新建工位信息.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] ComBaseStationCrInput input)
    {
        if (await _repository.AnyAsync(x => x.EnCode == input.enCode && x.DeleteMark == null))
            throw Oops.Oh(ErrorCode.COM1004);
        var entity = input.Adapt<ComBaseStationEntity>();
        entity.Id = SnowflakeIdHelper.NextId();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 更新工位信息.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] ComBaseStationUpInput input)
    {
        if (await _repository.AnyAsync(x => x.EnCode == input.enCode && x.DeleteMark == null && x.Id != id))
            throw Oops.Oh(ErrorCode.COM1004);
        var entity = input.Adapt<ComBaseStationEntity>();
        var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
        {
            it.ParentId,
            it.EnCode,
            it.FullName,
            it.SortCode,
            it.Description,
            it.EnabledMark,
            it.LastModifyTime,
            it.LastModifyUserId
        }).CallEntityMethod(m => m.LastModify()).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除工位信息.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Updateable<ComBaseStationEntity>().SetColumns(it => new ComBaseStationEntity()
        {
            DeleteTime = DateTime.Now,
            DeleteMark = 1,
            DeleteUserId = _userManager.UserId
        }).Where(it => it.Id.Equals(id)).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1002);
        ////var isOk = await _repository.Context.Deleteable<QmsBaseStationEntity>().Where(it => it.Id.Equals(id)).ExecuteCommandAsync();
        ////if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1002);
        //var entity = await _repository.SingleAsync(x => x.Id == id && x.CreatorUserId == _userManager.UserId && x.DeleteMark == null);
        //var isOk = await _repository.Context.Updateable(entity).CallEntityMethod(m => m.Delete()).UpdateColumns(it => new { it.DeleteMark, it.DeleteTime, it.DeleteUserId }).ExecuteCommandHasChangeAsync();
        //if (!isOk)
        //    throw Oops.Oh(ErrorCode.COM1002);
    }
}